<template>
  <div class="video-stream-management">
    <!-- 上部分：搜索和筛选 - 暂时隐藏 -->
    <!-- 
    <div class="filter-bar">
      <div class="search-filter">
        <el-input
          v-model="searchForm.streamTitle"
          placeholder="搜索标题"
          clearable
          @keyup.enter="handleSearch"
          style="width: 200px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="searchForm.status"
          placeholder="状态筛选"
          clearable
          style="width: 150px; margin-left: 15px"
        >
          <el-option label="全部" value="" />
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
        <el-button
          type="primary"
          @click="handleSearch"
          style="margin-left: 15px"
        >
          搜索
        </el-button>
        <el-button @click="handleReset" style="margin-left: 10px">
          重置
        </el-button>
      </div>
    </div>
    -->

    <!-- 下部分：视频流表格 -->
    <div class="table-section">
      <div class="table-header">
        <h3>视频流列表</h3>
        <div class="table-controls">
          <el-button
            size="small"
            type="primary"
            @click="handleAdd"
            :icon="Plus"
          >
            新增视频流
          </el-button>
          <el-button
            size="small"
            @click="handleRefresh"
            :icon="Refresh"
            :loading="loading"
          >
            刷新
          </el-button>

          <el-button
            size="small"
            type="danger"
            @click="handleBatchDelete"
            :disabled="selectedRows.length === 0"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <div class="table-container">
        <el-table
          :data="tableData"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          :header-cell-style="{
            background: '#f8f9fa',
            color: '#333',
            fontWeight: '500',
            textAlign: 'center',
          }"
          :cell-style="{ textAlign: 'center' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />

          <el-table-column
            prop="streamTitle"
            label="标题"
            min-width="150"
            align="center"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <div class="title-cell">
                <!-- <el-icon class="video-icon"><VideoCamera /></el-icon> -->
                <span>{{ row.streamTitle || row.title }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="previewUrl"
            label="预览链接"
            min-width="200"
            align="center"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <el-link type="primary" @click="copyToClipboard(row.previewUrl || row.streamUrl)">
                {{ row.previewUrl || row.streamUrl }}
              </el-link>
            </template>
          </el-table-column>

          <el-table-column
            prop="captureUrl"
            label="采集链接"
            min-width="200"
            align="center"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <el-link type="primary" @click="copyToClipboard(row.captureUrl || row.streamUrl)">
                {{ row.captureUrl || row.streamUrl }}
              </el-link>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="{ row }">
              <div class="time-cell">
                <el-icon><Clock /></el-icon>
                <span>{{ formatDateTime(row.createTime) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="remark"
            label="备注"
            min-width="150"
            align="center"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <span v-if="row.remark">{{ row.remark }}</span>
              <span v-else class="text-muted">无</span>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            width="230"
            align="center"
            fixed="right"
          >
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click="handleEdit(row)">
                  编辑
                </el-button>

                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ pagination.total }} 条记录，当前显示第 {{ (pagination.currentPage - 1) * pagination.pageSize + 1 }} - {{ Math.min(pagination.currentPage * pagination.pageSize, pagination.total) }} 条</span>
        </div>
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          size="small"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="streamTitle">
          <el-input v-model="form.streamTitle" placeholder="请输入视频流标题" />
        </el-form-item>

        <el-form-item label="预览链接" prop="previewUrl">
          <el-input
            v-model="form.previewUrl"
            placeholder="请输入视频预览流URL"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <el-form-item label="采集链接" prop="captureUrl">
          <el-input
            v-model="form.captureUrl"
            placeholder="请输入视频采集流URL"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <el-form-item label="排序" prop="streamSort">
          <el-input-number v-model="form.streamSort" :min="1" :max="999" placeholder="请输入排序值" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入备注信息"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Refresh,
  Search,
  RefreshLeft,
  Edit,
  Delete,
  Connection,
  VideoCamera,
  Clock,
} from "@element-plus/icons-vue";

// 响应式数据
const loading = ref(false);
const submitting = ref(false);
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' | 'edit'
const selectedRows = ref([]);
const formRef = ref();

// 搜索表单 - 暂时隐藏
// const searchForm = reactive({
//   streamTitle: "", // 更新为API文档中的字段名
//   status: "",
// });

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10, // 修改为默认10条
  total: 0,
});

// 表单数据
const form = reactive({
  id: null,
  streamTitle: "",
  previewUrl: "",
  captureUrl: "",
  streamSort: 1,
  status: "0", // 默认正常状态
  remark: "",
});

// 表单验证规则
const rules = {
  streamTitle: [
    { required: true, message: "请输入标题", trigger: "blur" },
    { min: 2, max: 50, message: "标题长度在 2 到 50 个字符", trigger: "blur" },
  ],
  previewUrl: [
    { required: true, message: "请输入预览链接", trigger: "blur" },
  ],
  captureUrl: [
    { required: true, message: "请输入采集链接", trigger: "blur" },
  ],
  streamSort: [
    { required: true, message: "请输入排序值", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 表格数据 - 移除模拟数据，完全依赖API
const tableData = ref([]);

// 计算属性
const dialogTitle = computed(() => {
  return dialogType.value === "add" ? "新增视频源" : "编辑视频源";
});

// 方法
const getStatusType = (status) => {
  // 支持API文档中的数字状态和字符串状态
  const statusMap = {
    '0': "success",    // 正常
    '1': "danger",     // 停用
    online: "success",
    offline: "danger",
    checking: "warning",
  };
  return statusMap[status] || "info";
};

const getStatusText = (status) => {
  // 支持API文档中的数字状态和字符串状态
  const statusMap = {
    '0': "正常",
    '1': "停用",
    online: "在线",
    offline: "离线",
    checking: "检测中",
  };
  return statusMap[status] || "未知";
};

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString("zh-CN");
};

const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success("链接已复制到剪贴板");
  } catch (error) {
    ElMessage.error("复制失败");
  }
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 导入API模块
    const { videoStreamAPI } = await import("../api/index.js");

    try {
      // 调用API接口 - 根据实际参数更新
      const requestParams = {
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize,
        orderByColumn: 'streamSort',
        isAsc: 'desc'
      };
      
      console.log('📡 发送API请求参数:', requestParams);
      console.log('📡 参数类型检查:', {
        pageNum: typeof requestParams.pageNum,
        pageSize: typeof requestParams.pageSize,
        orderByColumn: typeof requestParams.orderByColumn,
        isAsc: typeof requestParams.isAsc
      });
      console.log('📡 当前分页状态:', { ...pagination });
      
      const response = await videoStreamAPI.getVideoStreams(requestParams);

      console.log('API响应数据:', response); // 调试信息
      
      if (response && response.code == 0) { // 根据API文档返回格式
        // 直接使用response根级别的rows和total字段
        console.log('API数据详情:', response); // 调试信息
        
        tableData.value = response.rows || [];
        pagination.total = response.total || 0;
        
        console.log('处理后的表格数据:', tableData.value); // 调试信息
        console.log('总数:', pagination.total); // 调试信息
      } else {
        throw new Error(response?.msg || "API返回数据格式错误");
      }
    } catch (apiError) {
      console.error("API调用失败:", apiError.message);
      ElMessage.error("加载数据失败，请检查网络连接");
      
      // API失败时，清空数据
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索功能暂时隐藏
// const handleSearch = () => {
//   pagination.currentPage = 1;
//   loadData();
// };

// const handleReset = () => {
//   searchForm.streamTitle = "";
//   searchForm.status = "";
//   pagination.currentPage = 1;
//   loadData();
// };

// 刷新
const handleRefresh = () => {
  loadData();
};

// 新增
const handleAdd = () => {
  dialogType.value = "add";
  resetForm();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  dialogType.value = "edit";
  // 映射API字段到表单字段
  Object.assign(form, {
    id: row.streamId,
    streamTitle: row.streamTitle || row.title,
    previewUrl: row.previewUrl || row.streamUrl,
    captureUrl: row.captureUrl || row.streamUrl,
    streamSort: row.streamSort || 1,
    status: row.status,
    remark: row.remark,
  });
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除视频源 "${row.streamTitle || row.title}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 导入API模块
    const { videoStreamAPI } = await import("../api/index.js");

    try {
      console.log('单个删除的ID:', row.streamId);
      console.log('ID类型:', typeof row.streamId);
      console.log('行数据:', row);
      
      const response = await videoStreamAPI.deleteVideoStream(row.streamId);
      if (response && response.code == 0) {
        ElMessage.success("删除成功");
      } else {
        throw new Error(response?.msg || "删除失败");
      }
    } catch (apiError) {
      console.error("API删除失败:", apiError.message);
      ElMessage.error("删除失败，请检查网络连接");
    }

    loadData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};



// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的视频源");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个视频源吗？`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 导入API模块
    const { videoStreamAPI } = await import("../api/index.js");

    try {
      const idsToDelete = selectedRows.value.map(row => row.streamId);
      console.log('批量删除的ID数组:', idsToDelete);
      console.log('ID数组类型:', typeof idsToDelete);
      console.log('是否为数组:', Array.isArray(idsToDelete));
      
      const response = await videoStreamAPI.batchDeleteVideoStreams(idsToDelete);
      if (response && response.code == 0) {
        ElMessage.success("批量删除成功");
      } else {
        throw new Error(response?.msg || "批量删除失败");
      }
    } catch (apiError) {
      console.error("API批量删除失败:", apiError.message);
      ElMessage.error("批量删除失败，请检查网络连接");
    }

    selectedRows.value = [];
    loadData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量删除失败");
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    // 导入API模块
    const { videoStreamAPI } = await import("../api/index.js");

    if (dialogType.value === "add") {
      try {
        // 添加调试信息
        const addData = {
          streamTitle: form.streamTitle,
          previewUrl: form.previewUrl,
          captureUrl: form.captureUrl,
          streamSort: form.streamSort,
          status: form.status,
          remark: form.remark
        };
        
        console.log('新增表单数据:', form);
        console.log('发送给API的数据:', addData);
        
        // 根据API文档更新参数
        const response = await videoStreamAPI.addVideoStream(addData);
        
        console.log('新增API响应:', response);
        
        if (response && response.code == 0) {
          ElMessage.success("新增成功");
        } else {
          throw new Error(response?.msg || "新增失败");
        }
      } catch (apiError) {
        console.error("API新增失败:", apiError.message);
        ElMessage.error("新增失败，请检查网络连接");
      }
    } else {
      try {
        // 根据API文档更新参数
        const response = await videoStreamAPI.updateVideoStream(form.id, {
          streamTitle: form.streamTitle,
          previewUrl: form.previewUrl,
          captureUrl: form.captureUrl,
          streamSort: form.streamSort,
          status: form.status,
          remark: form.remark
        });
        
        if (response && response.code == 0) {
          ElMessage.success("更新成功");
        } else {
          throw new Error(response?.msg || "更新失败");
        }
      } catch (apiError) {
        console.error("API更新失败:", apiError.message);
        ElMessage.error("更新失败，请检查网络连接");
      }
    }

    dialogVisible.value = false;
    loadData();
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败");
  } finally {
    submitting.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    streamTitle: "",
    previewUrl: "",
    captureUrl: "",
    streamSort: 1,
    status: "0", // 默认正常状态
    remark: "",
  });
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 分页变化
const handleSizeChange = (size) => {
  console.log('🔄 页面大小变化:', size);
  console.log('🔄 变化前分页状态:', { ...pagination });
  pagination.pageSize = size;
  pagination.currentPage = 1;
  console.log('🔄 变化后分页状态:', { ...pagination });
  console.log('📊 发送给API的分页参数:', { pageSize: pagination.pageSize, currentPage: pagination.currentPage });
  loadData();
};

const handleCurrentChange = (page) => {
  console.log('🔄 当前页变化:', page);
  console.log('🔄 变化前分页状态:', { ...pagination });
  pagination.currentPage = page;
  console.log('🔄 变化后分页状态:', { ...pagination });
  console.log('📊 发送给API的分页参数:', { pageSize: pagination.pageSize, currentPage: pagination.currentPage });
  loadData();
};

// 组件挂载
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.video-stream-management {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 搜索栏样式暂时隐藏
.filter-bar {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.search-filter {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
*/

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
  position: relative;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.table-controls {
  display: flex;
  gap: 10px;
}

.table-container {
  flex: 1;
  overflow: auto;
  padding: 0 20px;
  min-height: 0;
}

.title-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.video-icon {
  color: #409eff;
  font-size: 16px;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.action-buttons {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 5px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  flex-shrink: 0;
  background: white;
  margin-top: auto;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-stream-management {
    padding: 10px;
    height: 100%;
  }
  
  /* 搜索栏响应式样式暂时隐藏
  .filter-bar {
    margin-bottom: 10px;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  */
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .table-controls {
    width: 100%;
    justify-content: flex-end;
  }
  
  .table-container {
    padding: 0 10px;
  }
  
  .pagination-container {
    padding: 10px;
  }
}
</style>
